<template>
  <div class="analysis-container">
    <!-- Sidebar -->
    <AnalysisSidebar 
        :active-view="activeView"
        :all-plugins="allPlugins"
        @update:activeView="(val) => activeView = val"
        @select-plugin="handlePluginSelect"
        @import="showImportModal = true"
    />

    <!-- Main Content -->
    <main class="analysis-main">
      <!-- Header -->
      <header class="analysis-header">
        <div class="header-left">
          <div class="title">🕵️‍♂️ 智能分析中心</div>
          <div class="divider"></div>
          
          <div class="subject-selector">
            <span class="selector-label">分析对象:</span>
            <select v-model="selectedSubjectId" @change="handleSubjectChange">
                <option value="">[全量模式] 分析所有数据</option>
                <option v-for="s in allSubjects" :key="s.id" :value="s.id">
                {{ s.name }}
                </option>
            </select>
          </div>
        </div>

        <div class="header-right">
             <button class="btn-primary" @click="toggleAnalysisMode" :disabled="analyzing">
                {{ showAnalysisConfig ? '🔙 返回报告' : '🚀 新建分析' }}
             </button>
        </div>
      </header>

      <!-- Analysis Config Mode -->
      <AlgoConfigPanel 
         v-if="showAnalysisConfig"
         :all-plugins="allPlugins"
         v-model:selected-algorithms="selectedAlgorithms"
         :analyzing="analyzing"
         :current-params="currentParams"
         @run="runBatchAnalysis"
         @update-single-param="updateParam"
      />

      <!-- Report Mode -->
      <ReportViewer 
         v-else
         :analyzing="analyzing"
         :current-report="currentReport"
         :active-view="activeView"
         :completed-count="completedCount"
         :total-count="totalCount"
         @select-detail="handlePluginSelect"
         @rerun="runSingle"
      />

    </main>

    <!-- Modals -->
    <AlgorithmImportModal v-model:visible="showImportModal" @success="refreshPlugins" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { SubjectService } from '@/services/analysis/SubjectService'
import AlgorithmImportModal from './components/AlgorithmImportModal.vue'

// New Sub-components
import AnalysisSidebar from './analysis/AnalysisSidebar.vue'
import AlgoConfigPanel from './analysis/AlgoConfigPanel.vue'
import ReportViewer from './analysis/ReportViewer.vue'

const route = useRoute()

// Data
const allSubjects = ref([])
const selectedSubjectId = ref('')
const allPlugins = ref([])

const showImportModal = ref(false)
const showAnalysisConfig = ref(false)
const analyzing = ref(false)

const activeView = ref('overview')
const selectedAlgorithms = ref([])
const currentParams = reactive({}) // pluginId -> params obj

const currentReport = ref(null)

const totalCount = computed(() => selectedAlgorithms.value.length)
const completedCount = ref(0)

// Lifecycle
onMounted(async () => {
    const caseId = route.query.caseId
    if (caseId) {
        allSubjects.value = await SubjectService.extractSubjectsWithCache(caseId)
        await refreshPlugins()
        await tryLoadReport()
    }
})

// Methods
const refreshPlugins = async () => {
    allPlugins.value = await window.electronAPI.analysis.listPlugins()
}

const tryLoadReport = async () => {
    const caseId = route.query.caseId
    const res = await window.electronAPI.analysis.loadReport(caseId, selectedSubjectId.value || null)
    if (res) {
        currentReport.value = res
        showAnalysisConfig.value = false
    } else {
        currentReport.value = null
        showAnalysisConfig.value = true // Auto show creation if no report
    }
}

const handleSubjectChange = async () => {
    await tryLoadReport()
}

const toggleAnalysisMode = () => {
    showAnalysisConfig.value = !showAnalysisConfig.value
}

const updateParam = (pluginId, params) => {
    currentParams[pluginId] = params
}

const runBatchAnalysis = async () => {
    analyzing.value = true
    completedCount.value = 0
    const results = []
    const caseId = route.query.caseId
    
    try {
        for (const pid of selectedAlgorithms.value) {
            const plugin = allPlugins.value.find(p => p.id === pid)
            const params = currentParams[pid] || {}
            
            // Deep copy to remove reactivity
            const runParams = JSON.parse(JSON.stringify(params))
            
            if (selectedSubjectId.value) {
                runParams.subjectId = selectedSubjectId.value
                const subject = allSubjects.value.find(s => s.id === selectedSubjectId.value)
                if (subject) {
                     runParams.subjectName = subject.name
                }
                if (subject && subject.accounts) {
                    // Deep copy accounts
                    runParams.accounts = JSON.parse(JSON.stringify(subject.accounts))
                }
            }

            // Using JSON copy to ensure it's cloneable
            const res = await window.electronAPI.analysis.runPlugin(pid, caseId, runParams)
            
            if (res.success) {
                results.push({
                    type: pid, 
                    pluginId: pid,
                    pluginName: plugin.name,
                    data: res.data,
                    meta: res.meta
                })
            }
            
            completedCount.value++
        }
        
        // Save Report
        const reportData = {
            subjectName: selectedSubjectId.value ? allSubjects.value.find(s => s.id === selectedSubjectId.value)?.name : '全量数据',
            results: results
        }
        
        // Deep copy report data before saving to IPC
        const cleanReportData = JSON.parse(JSON.stringify(reportData))
        
        await window.electronAPI.analysis.saveReport(caseId, selectedSubjectId.value || null, cleanReportData)
        currentReport.value = await window.electronAPI.analysis.loadReport(caseId, selectedSubjectId.value || null)
        showAnalysisConfig.value = false
        activeView.value = 'overview'

    } catch (e) {
        console.error(e)
        alert('分析过程中出错: ' + e.message)
    } finally {
        analyzing.value = false
    }
}

const handlePluginSelect = (plugin) => {
    // support passing plugin object or result object
    const id = plugin.id || plugin.type || plugin.pluginId
    activeView.value = id
    showAnalysisConfig.value = false
}

const runSingle = async (pid) => {
    if (!currentReport.value) return
    
    analyzing.value = true
    try {
        const caseId = route.query.caseId
        const params = currentParams[pid] || {} 
        const runParams = JSON.parse(JSON.stringify(params))
        
        if (selectedSubjectId.value) {
             runParams.subjectId = selectedSubjectId.value
             const subject = allSubjects.value.find(s => s.id === selectedSubjectId.value)
             if (subject && subject.accounts) {
                 runParams.accounts = JSON.parse(JSON.stringify(subject.accounts))
             }
        }
        
        const res = await window.electronAPI.analysis.runPlugin(pid, caseId, runParams)
        
        if (res.success) {
            const newResItem = {
                type: pid,
                pluginId: pid,
                pluginName: allPlugins.value.find(p => p.id === pid)?.name,
                data: res.data,
                meta: res.meta
            }
            
            // Replace in report
            const newResults = currentReport.value.results.filter(r => r.type !== pid && r.pluginId !== pid)
            newResults.push(newResItem)
            
            const newReport = {
                ...currentReport.value,
                results: newResults
            }
            
            const cleanReport = JSON.parse(JSON.stringify(newReport))
            
            await window.electronAPI.analysis.saveReport(caseId, selectedSubjectId.value || null, cleanReport)
            currentReport.value = await window.electronAPI.analysis.loadReport(caseId, selectedSubjectId.value || null)
        }
    } catch(e) {
        alert(e.message)
    } finally {
        analyzing.value = false
    }
}

</script>

<style scoped>
.analysis-container {
    display: flex;
    height: 100%;
    background: #f0f2f5;
}

.analysis-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.analysis-header {
    height: 60px;
    background: white;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 1px 4px rgba(0,0,0,0.05);
    z-index: 10;
}

.header-left { display: flex; align-items: center; gap: 20px; }
.title { font-size: 18px; font-weight: bold; }
.divider { width: 1px; height: 20px; background: #ddd; }
.subject-selector { display: flex; align-items: center; gap: 10px; font-size: 14px; }
select { padding: 5px; border: 1px solid #dcdfe6; border-radius: 4px; }

.btn-primary {
    background: #409eff;
    color: white;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
    font-weight: 500;
}
.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
</style>
